import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { useUserStore } from "@/store/modules/user";

// 创建 axios 实例
const service = axios.create({
  // baseURL: import.meta.env.VITE_APP_ADMIN_API,
  timeout: 50000,
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStore();

    config.headers.Authorization = `Bearer ${userStore.$state.token}`;
    config.headers.appid = userStore.user?.userAppid; //  userAppid: 用户小程序id
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { message } = response.data;
    // 请求状态为 200 // 暂不对code处理
    // if (response.status === 200 && response.statusText === "OK") {
    //   return response.data;
    // } else {
    //   return Promise.reject(new Error(message || "Error"));
    // }
    return Promise.resolve(response.data);
  },
  (error: any) => {
    if (error.response.status === 401) {
      const userStore = useUserStore();
      ElMessage.error("登录失效，请重新登录");
      userStore.clearToken();
      localStorage.removeItem("userAppid");
      localStorage.removeItem("userApps");
      userStore.user.name = "";
      nextTick(() => {
        window.location.href = `/login`;
      });
      return false;
    }

    if (error.response.data && error.response.config.responseType !== "blob") {
      error.response.data.message =
        error.response.data.msg || error.response.data.message;
      const { message } = error.response.data;
      ElMessage.error(message || "请求服务异常");
    }

    return Promise.reject(error);
  }
);

// 导出 axios 实例
export default service;
